package servlets;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import structures.Product;
import structures.ProductList;
import managers.JsonHelper;
import managers.JsonManager;
import managers.SignedRequestsHelper;

public class SearchKeywordsServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	private static final String AWS_ACCESS_KEY_ID = "AKIAIWIOLZ7WSLYBCSEA";
	private static final String AWS_SECRET_KEY = "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";
	private static final String ENDPOINT = "webservices.amazon.co.uk";
	//
	//private static final String IMAGE_URL_SEARCH = "http://localhost:8080/AmazonRESTWebService/productImage?";
	private static final String IMAGE_URL_SEARCH = "http://amazonrestservice.herokuapp.com/productImage?";
	
	private static final int MAX_RESULTS = 3;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) {
		JsonManager manager = new JsonManager();
		ProductList productList = new ProductList();
		JsonHelper jsonHelper = new JsonHelper();
		String keywords = request.getParameter("keywords");
		JSONObject root = new JSONObject();
		String result = "";
		String inputLine, answer = "";
		BufferedReader reader;
		StringBuffer responseBuffer;
		
		
		SignedRequestsHelper helper;
        try {
            helper = SignedRequestsHelper.getInstance(ENDPOINT, AWS_ACCESS_KEY_ID, AWS_SECRET_KEY);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        
        String requestUrl = null;
        
        Map<String, String> params = new HashMap<String, String>();
        params.put("Service", "AWSECommerceService");
        params.put("Version", "2011-08-01");
        params.put("Operation", "ItemSearch");
        params.put("Keywords", keywords);
        params.put("SearchIndex", "Blended");
        params.put("Availability", "Available");
        params.put("AssociateTag", "wwwmarcoden-21");
        
        requestUrl = helper.sign(params);
        
        try {
        	root = jsonHelper.fromXMLtoJson(requestUrl);
        	
        	JSONObject root1 = root.getJSONObject("ItemSearchResponse");
        	JSONObject items = root1.getJSONObject("Items");
        	JSONArray item = items.getJSONArray("Item");
        	
        	JSONObject res = new JSONObject();
        	
        	for(int i = 0; i < MAX_RESULTS; i++) {
	        	JSONObject obj = item.getJSONObject(i);
	        	if(obj.has("DetailPageURL")) {
	        		
	        		// Retrieving the image
		    		String url = IMAGE_URL_SEARCH + "id=" + obj.get("ASIN");
		    		String cleanUrl = url.replace(" ", "%20");
		    		
		    		HttpURLConnection httpConnection = (HttpURLConnection) new URL(cleanUrl).openConnection();
		    		httpConnection.setRequestMethod("GET");
		    		httpConnection.setDoOutput(true); 
		    		httpConnection.setDoInput(true);
		    		httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		    		
		    		reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));

		    		responseBuffer = new StringBuffer();
		    		
		    		while ((inputLine = reader.readLine()) != null) {
		    			responseBuffer.append(inputLine);
		    		}
		    		reader.close();
		    		// Here's the image's link
		    		answer = responseBuffer.toString();
	        		
		        	res.put("type", "amazon");
		        	res.put("image", answer);
		        	res.put("title", obj.getJSONObject("ItemAttributes").get("Title").toString());
		        	res.put("link", obj.get("DetailPageURL").toString());
		        	res.put("id", obj.get("ASIN").toString());
		        
		        	String product = res.toString();
		        	product = product.replace("[", "");
		        	product = product.replace("]", "");
		        	Product p = new Product();
		        	p = manager.toProduct(product);
		        	
		        	productList.getList().add(p);
		        	
		        	//result += res.toString();
		        	}
	        }
        	
        	String listP = manager.generateJSON(productList);
        	
        	response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
        	response.getWriter().write(listP);
        } catch(Exception e) {
        }
	}
	
	private static String fetchTitle(String requestUrl) {
        String title = null;
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(requestUrl);
            Node titleNode = doc.getElementsByTagName("Title").item(0);
            title = titleNode.getTextContent();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return title;
    }
	
	private static JSONObject fromXMLtoJson(String requestUrl) throws JSONException
	{
		JSONObject obj = new JSONObject();
		String output = "";
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	        DocumentBuilder db = dbf.newDocumentBuilder();
	        Document doc = db.parse(requestUrl);
	       
	        TransformerFactory tf = TransformerFactory.newInstance();
	        Transformer transformer = tf.newTransformer();
	        StringWriter writer = new StringWriter();
	        transformer.transform(new DOMSource(doc), new StreamResult(writer));
	        output = writer.getBuffer().toString().replaceAll("\n|\r", "");
		} catch (Exception e) {
            throw new RuntimeException(e);
        }
		obj = XML.toJSONObject(output);
		
		System.out.println(obj.toString());
		
		return obj;
	}
	


}
